<?php
/**
 * Created by Administrator
 * User: longli
 * VX: isa1589518286
 * Date: 2020/08/12
 * Time: 10:50
 * @link http://www.lmterp.cn
 */

namespace app\common\service\platform;


use app\common\library\Tools;
use app\common\model\AccountSyncLog;
use app\common\model\Orders;
use app\common\model\OrdersTemp;
use app\common\service\orders\OrderService;
use Exception;
use GuzzleHttp\Client;
use think\facade\Log;

/**
 * 新蛋接口服务
 * Class NeweggService
 * @package app\common\service\newegg
 * @link https://developer.newegg.com/newegg_marketplace_api/
 */
class NeweggService extends BasePlatformService
{
    public static $tokenField = [
        'required' => [ // 必填字段
            [
                'type' => 'text',
                'name' => 'access_key',
                'field' => 'access_key',
            ],
            [
                'type' => 'text',
                'name' => 'secret_key',
                'field' => 'secret_key',
            ],

        ],
        'option' => [ // 可选字段
        ],
    ];

    /**
     * http 客户端
     * @var Client
     */
    protected $client;

    public function init()
    {
        $this->client = new Client(['base_uri' => $this->getBaseUrl(), 'timeout' => 10]);
    }

    /**
     * 获取订单列表
     * @param array $params 参数配置，默认抓取当天订单
     * <ul>
     * <li>string start_date 抓取开始时间，默认为今天</li>
     * <li>string end_date 抓取结束时间，默认为当前时间</li>
     * <li>int status 订单状态，默认为0</li>
     * </ul>
     * @param bool $replace 是否替换原有的订单，默认不替换
     * @date 2020/08/13
     * @author longli
     */
    public function getOrderList($params = [], $replace = false)
    {
        $startSyncTime = time();
        Log::info(sprintf("newegg 批量同步账号【%d】订单，请求参数: 【%s】", $this->getAccountId(), json_encode($params)));
        $account = $this->getAccount();
        $totalPage = $page = 1;
        $pageSize = !empty($params['page_size']) && $params['page_size'] < 101 ? $params['page_size'] : 100;
        $args = [
            'OperationType' => 'GetOrderInfoRequest',
            'RequestBody' => [
                'PageSize' => $pageSize,
                'PageIndex' => & $page,
                'RequestCriteria' => [
                    'Status' => !empty($params['status']) ? $params['status'] : 0,
                    'OrderDateFrom' => !empty($params['start_date']) ? $params['start_date'] : date('Y-m-d'),
                    'OrderDateTo' => !empty($params['end_date']) ? $params['end_date'] : date('Y-m-d H:i:s')
                ]
            ]
        ];
        do
        {
            try
            {
                $response = $this->client->put("/marketplace/ordermgmt/order/orderinfo?sellerid={$account->store_name}&version=307", [
                    "body" => json_encode($args),
                    "headers" => $this->getHeader(),
                ])->getBody()->getContents();
                $orderData = json_decode($response, true);
                if (!$orderData['IsSuccess']) {
                    Log::info(sprintf("newegg 获取订单异常账号【%d】，响应信息【%s】", $this->getAccountId(), json_encode($orderData)));
                    break;
                }
                if(empty($orderData['ResponseBody']['OrderInfoList'])) break; // 无订单数据
                $totalPage = $orderData['ResponseBody']['PageInfo']['TotalPageCount']; // 总页数
                foreach ($orderData['ResponseBody']['OrderInfoList'] as $order)
                {
                    $this->pushOrderToTemp($order['OrderNumber'], $order, $replace);
                }
                $page++;
            }catch(Exception $e)
            {
                Log::info(sprintf("newegg 获取订单异常，账号【%d】，错误信息：【%s】", $this->getAccountId(), $e->getMessage()));
                break;
            }
        }while($page <= $totalPage);
        // 添加同步订单日志
        AccountSyncLog::addLog($this->getAccountId(), $startSyncTime, time(), $params);
    }

    public function markDelivery($orderIds = [])
    {
        foreach($this->getNeedMarkOrders($orderIds) as $order)
        {
            $orderId = $order->order_no;
            $sellerId = $order->account->store_name;
            $package = [];
            foreach($order->detail as $detail)
            {
                $package[] = [
                    'TrackingNumber' => $order->track_num,
                    'ShipCarrier'    => $order->logistics_name,
                    'ShipService'    => date('Y-m-d H:i:s', strtotime("+15day")),
                    'ItemList'       => [
                        'Item'  => [
                            'SellerPartNumber' => $detail->platform_sku,
                            'ShippedQty' => $detail->qty,
                        ]
                    ]
                ];
            }
            $args = [
                'Action' => '2',
                'Value' => [
                    'Shipment' => [
                        'Header' => [
                            'SellerID' => $sellerId,
                            'SONumber' => $orderId,
                        ],
                        'PackageList' => $package
                    ]
                ]
            ];
            try
            {
                $response = $this->client->put("marketplace/ordermgmt/orderstatus/orders/{$orderId}?sellerid={$sellerId}&version=304", [
                    "body" => json_encode($args),
                    "headers" => $this->getHeader(),
                ])->getBody()->getContents();
                $json = json_decode($response, true);
                if(!$json['IsSuccess'])
                {
                    Log::info(sprintf("Newegg 订单号【%s】标记失败，错误信息【%s】", $order->order_no, $response));
                    continue;
                }
                $order->is_flag_sent = Orders::FLAG_SENT_YES;
                $order->sent_time = Tools::now();
                $order->save();
            }catch(Exception $e)
            {
                Log::info(sprintf("Newegg 订单号【%s】标记请求异常，错误信息【%s】", $order->order_no, $e->getMessage()));
            }
        }
    }

    /**
     * 获取请求头信息
     * @return array 返回请求头信息
     * @date 2020/08/14
     * @author longli
     */
    public function getHeader()
    {
        $account = $this->getAccount();
        return [
            "Authorization" => $account->token->access_key,
            "SecretKey" => $account->token->secret_key,
            "Content-Type" => "application/json",
            "Accept" => "application/json"
        ];
    }

    /**
     * @inheritDoc
     */
    public function syncOrder(OrdersTemp $ordersTemp)
    {
        $data = $ordersTemp->order_info;
        $info = [];
        foreach($data['ItemInfoList'] as $item)
        {
            $info[] = [
                "qty"           => $item['OrderedQty'], // 数量
                "return_qty"    => 0, // 取消数量
                "price"         => $item['UnitPrice'], // 售价
                "platform_sku"  => $item['SellerPartNumber'], // sku
                "name"          => $item['Description'], // 产品名称
                'url'           => "https://www.newegg.com/p/123123?Item={$item['NeweggItemNumber']}", // 商品在线地址
            ];
        }
        $platform = $this->getAccountById($ordersTemp->account_id)->platform;
        $order = [
            "order_no"                  => $ordersTemp->order_no,
            "account_id"                => $ordersTemp->account_id,
            "platform_name"             => $platform->name, // 平台名称
            "order_platform_status"     => $data['OrderStatusDescription'], // 订单在平台的状态
            "buyer_first_name"          => $data['ShipToFirstName'], // 客户名称
            "buyer_last_name"           => $data['ShipToLastName'], // 客户名称
            "buyer_phone"               => $data["CustomerPhoneNumber"], // 电话
            "country"                   => 'America', // 国家
            "buyer_country_code"        => 'US', // 国家编码
            "buyer_province"            => $data['ShipToStateCode'], // 省，州
            "buyer_city"                => $data['ShipToCityName'], // 城市
            "buyer_post_code"           => $data['ShipToZipCode'], // 邮编
            "buyer_address_1"           => $data['ShipToAddress1'], // 买家收货地址1
            "buyer_address_2"           => $data['ShipToAddress2'], // 买家收货地址2
            "buyer_email"               => $data['CustomerEmailAddress'], // 买家邮箱
            "shipping_price"            => $data['ShippingAmount'], // 订单运费
            "order_source_create_time"  => $this->parseTimeToDate($data['OrderDate']), // 订单在平台生成的时间
            "latest_delivery_time"      => $this->parseTimeToDate(strtotime("10day")), // 最迟发货时间
            "order_price"               => $data['OrderItemAmount'], // 订单金额
            "total_price"               => $data['OrderItemAmount'] + $data['ShippingAmount'], // 订单总金额
            "order_pay_time"            => null, // 订单支付时间
            "currency"                  => 'USD', // 币种
            "track_num"             => null, // 追踪号
            "platform_remark"           => null, // 买家备注信息
            "order_detail" => $info,
        ];
        return OrderService::getInstance()->addOrder($order);
    }
}